package com.itic.web.mem.member.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.plugins.mybatis.Page;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.configuration.PropertyHelper;
import com.itic.ht.cms.exam.persistence.model.Exam;
import com.itic.ht.cms.exam.persistence.model.ExamExample;
import com.itic.ht.cms.exam.service.ExamService;
import com.itic.ht.cms.examrecord.persistence.model.ExamRecord;
import com.itic.ht.cms.examrecord.persistence.model.ExamRecordExample;
import com.itic.ht.cms.examrecord.service.ExamRecordService;
import com.itic.ht.cms.question.persistence.model.QuestionModel;
import com.itic.ht.cms.question.service.QuestionModelService;
import com.itic.ht.cms.questionselection.persistence.model.QuestionSelection;
import com.itic.ht.cms.questionselection.persistence.model.QuestionSelectionExample;
import com.itic.ht.cms.questionselection.service.QuestionSelectionService;
import com.itic.ht.file.webfile.persistence.model.WebFile;
import com.itic.ht.file.webfile.service.WebFileService;
import com.itic.ht.mem.member.persistence.model.WebMember;
import com.itic.ht.mem.member.service.WebMemberService;
import com.itic.ht.mem.memberdetail.persistence.model.WebMemberDetail;
import com.itic.ht.mem.memberdetail.persistence.model.WebMemberDetailExample;
import com.itic.ht.mem.memberdetail.service.WebMemberDetailService;
import com.itic.ht.mem.mtype.persistence.model.WebmType;
import com.itic.ht.mem.mtype.service.WebmTypeService;
import com.itic.web.mem.member.util.FormDataUtil;
import com.itic.web.mem.member.view.MemberView;
import com.itic.web.qo.TokenData;
import com.itic.web.ro.PageInfo;
import com.itic.web.ro.ResResult;
import com.itic.web.util.TokenUtil;

import net.sf.json.JSONObject;

@Service
@Transactional
public class AppMemberInfoService {
	private static final int QUESTION_NUM = 25;
	@Autowired
	private WebMemberService webMemberService;
	@Autowired
	private WebMemberDetailService memberDetailService;
	@Autowired
	private WebFileService webFileService;
	@Autowired
	private ExamService examService;
	@Autowired
	private ExamRecordService examRecordService;
	@Autowired
	private QuestionModelService questionModelService;
	@Autowired
	private QuestionSelectionService questionSelectionService;
	@Autowired
    private WebmTypeService typeService;

	/**
	 * 查询用户信息
	 */
	public ResResult getMemInfo(TokenData data) {

		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}

			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			// 取得用户信息
			WebMember member = webMemberService.getMemberByAccount(data.getAccount());
			System.out.println("现在要查询的帐号是:" + member.getAccount());
			//查询会员名称替换
			WebmType webmType = typeService.get(member.getCategory());

			String memfileId = member.getFileId();
			if (memfileId != null && !"".equals(memfileId)) {
				// ModelFiles file = modelFilesService.getFile(memfileId);
				WebFile webFile = webFileService.get(member.getFileId());
				if (webFile != null) {
					member.setFileId(webFile.getFilePath());
				}
			}

			// 过滤用户加密信息
			member.setVerificationCode(null);
			member.setPassword(null);
			member.setExpireTime(null);
			member.setVerificationExpireTime(null);
			Map<String, Object> resMap = new HashMap<>();
			WebmType wt = new WebmType();
			wt.setFileId(webmType.getFileId());
			wt.setName(webmType.getName());
			wt.setLevel(webmType.getLevel());
			WebMemberDetail detail = memberDetailService.getMemberDetailByAccount(member.getAccount());
			resMap.put("memberDetail", detail);
			resMap.put("member", member);
			resMap.put("webmType", wt);
			
			return ResResult.build(200, "获取用户信息成功", resMap);
		} catch (Exception e) {
			// 返回错误代码
			return ResResult.error(4, "getMemInfo调用失败");
		}

	}

	/**
	 * 查询用户二维码
	 */
	public ResResult getMemCode(TokenData data) {

		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}

			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			// 取得用户信息
			WebMember member = webMemberService.getMemberByAccount(data.getAccount());
			System.out.println("现在要查询的帐号是:" + member.getAccount());

			WebMemberDetail detail = memberDetailService.getMemberDetailByAccount(member.getAccount());
			
            String invitationCode = detail.getInvitationCode();
            String url = PropertyHelper.getString("app.qcode.url");
            String httpGet = HttpRequestUtils.httpGet(url+"?url="+invitationCode);
    		JSONObject fromObject = JSONObject.fromObject(httpGet);
    		String resultRemote = fromObject.getString("errorCode");
    		if( "10000".equals(resultRemote)){
    			String fileId = fromObject.getString("data");
    			detail.setFileId(fileId);
    		}
    		
			return ResResult.build(200, "获取用户信息成功", detail);
		} catch (Exception e) {
			// 返回错误代码
			return ResResult.error(4, "getMemInfo调用失败");
		}

	}

	/**
	 * 更新用户姓名
	 */
	public ResResult updateMemName(TokenData data, String realname) {

		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}

			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			// 取得用户信息
			WebMember member = webMemberService.getMemberByAccount(data.getAccount());
			member.setRealname(realname);
			webMemberService.edit(member);
			System.out.println("现在要查询的帐号是:" + member.getAccount());

			// 变更图片
			String memfileId = member.getFileId();
			if (memfileId != null && !"".equals(memfileId)) {
				WebFile webFile = webFileService.get(member.getFileId());
				if (webFile != null) {
					member.setFileId(webFile.getFilePath());
				}
			}

			// 过滤用户加密信息
			member.setVerificationCode(null);
			member.setPassword(null);
			member.setExpireTime(null);
			member.setVerificationExpireTime(null);

			return ResResult.build(200, "更新用户信息成功", member);
		} catch (Exception e) {
			// 返回错误代码
			return ResResult.error(4, "updateMemName调用失败");
		}

	}

	/**
	 * 更新用户姓名
	 */
	public ResResult updateMemOSSImage(HttpServletRequest request, MultipartFile file, TokenData data) {

		WebMember member = null;
		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}

			System.out.println("*********************************1******************************");
			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			// 取得用户信息
			System.out.println("*********************************2******************************");
			member = webMemberService.getMemberByAccount(data.getAccount());
			System.out.println("现在要查询的帐号是:" + member.getAccount());
			System.out.println("*********************************3******************************");

			String originalFilename = file.getOriginalFilename();
			System.out.println("真实文件名是:" + originalFilename);
			String filePath = null;
			if (file != null && originalFilename != null && originalFilename.length() > 0) {
				System.out.println("*********************************4******************************");
				InputStream inputStream = null;
				try {
					System.out.println("*********************************5******************************");
					inputStream = file.getInputStream();
					filePath = FormDataUtil.inputStreamUpload("http://47.94.128.203:8080/FileServer/upload",
							inputStream, member.getAccount(), "1", "image", "T_WEB_MEMBER_TEMPLET");
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			System.out.println("*********************************6******************************");
			System.out.println("最后返回的图片地址是" + filePath);
			// 变更图片 保存用户图片到数据库
			String uuid = null;
			if (filePath != null) {
				System.out.println("*********************************7******************************");
				WebFile model = new WebFile();
				uuid = IdGen.uuid();
				model.setId(uuid);
				model.setFilePath(filePath);
				webFileService.add(model);
			}
			System.out.println("*********************************8******************************");
			member.setFileId(uuid);
			webMemberService.edit(member);
			if (member.getFileId() != null) {
				System.out.println("*********************************9******************************");
				WebFile webFile = webFileService.get(member.getFileId());
				if (webFile != null) {
					member.setFileId(webFile.getFilePath());
				}
			}

			// 过滤用户加密信息
			member.setVerificationCode(null);
			member.setPassword(null);
			member.setExpireTime(null);
			member.setVerificationExpireTime(null);

			return ResResult.build(200, "更新用户图片成功", member);
		} catch (Exception e) {
			// 返回错误代码
			return ResResult.error(4, "updateMemName调用失败");
		}

	}

	/**
	 * 我的团队
	 */
	public ResResult getMemUpRelation(TokenData data) {

		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}

			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			// 取得用户信息
			WebMember member = webMemberService.getMemberByAccount(data.getAccount());
			System.out.println("现在要查询的帐号是:" + member.getAccount());
			// 查出我的组织信息
			List<MemberView> masterviewList = new ArrayList<MemberView>();
			WebMemberDetail detail = memberDetailService.getMemberDetailByAccount(member.getAccount());

			System.out.println("**********************我的上级********************************************");
			System.out.println(detail.getAccount() + "的上级是:" + detail.getPid());
			System.out.println("***********************我的上级*******************************************");
			// 取得我的上级
			WebMember master = webMemberService.getMemberByAccount(detail.getPid());
			if (master != null) {
				MemberView masterview = new MemberView();
				masterview.setId(master.getId());
				masterview.setAccount(master.getAccount());
				masterview.setRealname(master.getRealname());
				// 用户头像地址
				String memfileId = master.getFileId();
				if (memfileId != null && !"".equals(memfileId)) {
					WebFile webFile = webFileService.get(master.getFileId());
					if (webFile != null) {
						masterview.setFileId(webFile.getFilePath());
					}
				}
				masterview.setPid(null);
				masterviewList.add(masterview);
			} else {
				masterviewList = new ArrayList<MemberView>();
			}

			return ResResult.build(200, "获取我的上级信息成功", masterviewList);
		} catch (Exception e) {
			// 返回错误代码
			return ResResult.error(4, "获取我的上级信息失败");
		}

	}

	/**
	 * 我的团队
	 */
	public ResResult getMemDownRelation(TokenData data, Page page) {

		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}
			// page对象不能为空
			if (page.getPageNow() > 0 && page.getPageSize() > 0) {
			} else {
				return ResResult.error(3, "page数据不能为空");
			}

			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			WebMember member = webMemberService.getMemberByAccount(data.getAccount());

			page.setRecordNow((page.getPageNow() - 1) * page.getPageSize());
			System.out.println("现在查询的是:" + page.getPageNow() + "页");
			System.out.println("现在查询的page初始序列号是:" + page.getRecordNow() + "个");
			System.out.println("现在查询的每页数据量是:" + page.getPageSize() + "个");
			System.out.println("查询到的用户帐号是" + member.getAccount());

			// 取得我的团队
			List<MemberView> viewlist = new ArrayList<MemberView>();
			WebMemberDetailExample detailExample = new WebMemberDetailExample();
			detailExample.createCriteria().andPidEqualTo(member.getAccount())
					.andDelFlagEqualTo(Integer.parseInt(DBConst.TRUE));
			detailExample.setOrderByClause("ctime desc");
			detailExample.setPage(page);
			// 获取信息总条数
			int total = memberDetailService.count(detailExample);
			System.out.println("现在查询的总条数是:" + total + "个");
			List<WebMemberDetail> detailList = memberDetailService.list(detailExample);
			if (detailList != null && detailList.size() > 0) {
				for (WebMemberDetail subMemDetail : detailList) {
					MemberView view = new MemberView();
					WebMember submember = webMemberService.getMemberByAccount(subMemDetail.getAccount());
					view.setId(submember.getId());
					view.setAccount(submember.getAccount());
					view.setRealname(submember.getRealname());
					view.setPid(subMemDetail.getPid());
					// 用户头像地址
					String memfileId = submember.getFileId();
					if (memfileId != null && !"".equals(memfileId)) {
						WebFile webFile = webFileService.get(submember.getFileId());
						if (webFile != null) {
							view.setFileId(webFile.getFilePath());
						}
					}

					viewlist.add(view);
				}
			} else {

			}

			PageInfo instance = PageInfo.getInstance(page.getPageNow(), page.getPageSize(), total);
			return ResResult.build(200, "获取我的团队信息成功", viewlist, instance);
		} catch (Exception e) {
			// 返回错误代码
			return ResResult.error(4, "获取我的团队失败");
		}

	}

	public ResResult assertSuperToken(TokenData data, String category, String etype,String isRandom) {
		try {
			// 判断token是不是存在
			if (StringHelper.isEmpty(data.getToken())) {
				return ResResult.error(1, "token不能为空");
			}
			// 先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if (!flag) {
				return ResResult.error(2, "token失效");
			}
			// 判断类型是否存在
			if (StringHelper.isBlank(category)) {
				return ResResult.error(3, "未选择题目类型");
			}

			// 从token中取account信息
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			WebMember member = webMemberService.getMemberByAccount(data.getAccount());
			// 判断考试类型
			if (DBConst.STUDY.equals(etype)) {
				// 考题学习 获取对应类型的试卷
				List<Map<String, Object>> list = getStuQesList(category);
				return ResResult.build(200, "获取考题学习成功", list);
			}

			// 考试
			if (DBConst.EXAM.equals(etype)) {
				// 先判断用户是否是会员
				if ("eba618aea92c49dba49cc82d70be52b0".equals(member.getCategory())) {
					return ResResult.error(4, "您没有权限考试，请先购买会员");
				}
				// 会员考试
				// 查询当前用户考试进度(根据账号和考试是否通过)
				ExamRecordExample example = new ExamRecordExample();
				example.createCriteria().andAccountEqualTo(member.getAccount()).andExamResultEqualTo(DBConst.FALSE);
				List<ExamRecord> list = examRecordService.list(example);
				int progress = 0;
				if(null!=null&&list.size()>0){
					ExamRecord examRecord = list.get(0);
					progress = Integer.parseInt(examRecord.getExamProgress())*QUESTION_NUM;
				}
				return getExamList(list, category, progress,isRandom);
				/*if (null == list || list.size() == 0) {
					// 取第一次考试的试卷和题目内容
					ExamExample examep = new ExamExample();
					examep.setOrderByClause("reorder asc");
					examep.createCriteria().andDelFlagEqualTo(Integer.parseInt(DBConst.TRUE))
							.andCategoryIdEqualTo(category).andReorderEqualTo(progress);
					List<Exam> examlist = examService.list(examep);
					if (null != examlist || examlist.size() == 0) {
						return ResResult.error(5, "当前分类暂无试卷");
					}
					Map<String, Object> resMap = new HashMap<>();
					Exam exam = examlist.get(0);
					// 查询对应试卷的题目
					List<QuestionModel> questionList = questionModelService.getExamQuestionList(progress, QUESTION_NUM,
							exam.getCategoryId());
					if (null != examlist || examlist.size() < QUESTION_NUM) {
						return ResResult.error(5, "当前分类暂无试卷");
					}
					Map<String, Object> qmMap = new HashMap<>();
					for (QuestionModel qm : questionList) {
						QuestionSelectionExample qmExample = new QuestionSelectionExample();
						qmExample.setOrderByClause("reorder asc");
						qmExample.createCriteria().andQuestionIdEqualTo(category);
						List<QuestionSelection> qsList = questionSelectionService.list(qmExample);
						qmMap.put("name", qm.getName());
						qmMap.put("id", qm.getId());
						qmMap.put("styleText", qm.getStyleText());
						qmMap.put("fileId", qm.getFileId());
						qmMap.put("tpoints", qm.getTpoints());
						qmMap.put("questionSelection", qsList);
					}
					resMap.put("id", exam.getId());
					resMap.put("examName", exam.getExamName());
					resMap.put("questionModel", qmMap);
				} else {
					return getExamList(list, category, progress);
				}
*/
			}
			return ResResult.error(5, "获取试题信息失败");
		} catch (Exception e) {
			return ResResult.error(5, "获取试题信息失败");
		}

	}

	/*
	 * 获取试卷信息
	 */
	private ResResult getExamList(List<ExamRecord> list, String category, int progress,String isRandom) {
		// 根据用户考试进度取试卷数据
		ExamExample examep = new ExamExample();
		examep.setOrderByClause("reorder asc");
		examep.createCriteria().andDelFlagEqualTo(Integer.parseInt(DBConst.TRUE)).andCategoryIdEqualTo(category)
				.andReorderEqualTo(progress);
		List<Exam> examlist = examService.list(examep);
		if (null == examlist || examlist.size() == 0) {
			return ResResult.error(5, "当前分类暂无试卷");
		}
		List<Map<String, Object>> resList = new ArrayList<>();
		Map<String, Object> resMap = new HashMap<>();
		Exam exam = examlist.get(0);
		// 查询对应试卷的题目
		List<QuestionModel> questionList = questionModelService.getExamQuestionList(progress, QUESTION_NUM,
				exam.getCategoryId(),isRandom);
		if (null == questionList || questionList.size() < QUESTION_NUM) {
			return ResResult.error(5, "当前分类暂无试卷");
		}
		for (QuestionModel qm : questionList) {
			Map<String, Object> qmMap = new HashMap<>();
			QuestionSelectionExample qmExample = new QuestionSelectionExample();
			qmExample.setOrderByClause("reorder asc");
			qmExample.createCriteria().andQuestionIdEqualTo(qm.getId());
			List<QuestionSelection> qsList = questionSelectionService.list(qmExample);
			if (null != qm.getName())qmMap.put("name", qm.getName());
			if (null != qm.getId())qmMap.put("id", qm.getId());
			if (null != qm.getStyleText())qmMap.put("styleText", qm.getStyleText());
			if (null != qm.getFileId())qmMap.put("fileId", qm.getFileId());
			if (null != qm.getTpoints())qmMap.put("tpoints", qm.getTpoints());
			if (null != qm.getSelectType())qmMap.put("selectType", qm.getSelectType());
			if (null != qm.getCategory())qmMap.put("category", qm.getCategory());			qmMap.put("questionSelection", qsList);
			resList.add(qmMap);
		}
		resMap.put("questionModel", resList);
		if (null != exam.getId())resMap.put("id", exam.getId());
		if (null != exam.getExamName())resMap.put("examName", exam.getExamName());
		return ResResult.build(200, "获取考题成功", resMap);
	}

	/*
	 * 获取题目列表
	 */
	private List<Map<String, Object>> getStuQesList(String category) {
		List<Map<String, Object>> resList = new ArrayList<>();
		List<QuestionModel> list = questionModelService.getQuestionList(category);
		// 去查每个问题所对应的选项
		if (null != list && list.size() > 0) {
			QuestionSelectionExample example = null;
			for (QuestionModel qm : list) {
				Map<String, Object> resMap = new HashMap<>();
				example = new QuestionSelectionExample();
				example.createCriteria().andQuestionIdEqualTo(qm.getId()).andIsEffectiveEqualTo(DBConst.TRUE);
				List<QuestionSelection> list2 = questionSelectionService.list(example);
				resMap.put("selection", list2);
				if (null != qm.getId())resMap.put("id", qm.getId());
				if (null != qm.getFileId())resMap.put("fileId", qm.getFileId());
				if (null != qm.getName())resMap.put("name", qm.getName());
				if (null != qm.getStyleText())resMap.put("styleText", qm.getStyleText());
				if (null != qm.getSelectType())resMap.put("selectType", qm.getSelectType());
				if (null != qm.getCategory())resMap.put("category", qm.getCategory());
				resList.add(resMap);
			}
		}
		return resList;
	}

}
